package org.chen.auth;

import com.alibaba.nacos.common.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

// AuthFilter.java
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private final WebClient webClient;

    @Autowired
    public AuthFilter(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("http://127.0.0.1:7010").build(); // 替换为你的服务地址
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (skipAuth(path)) {
            return chain.filter(exchange);
        }

        // 检查是否是内部调用
        if (isInternalCall(request)) {
            return chain.filter(exchange);
        }

        String token = getToken(request);
        if (token == null) {
            return unauthorizedResponse(exchange);
        }

        // **异步调用 Auth 服务进行 Token 验证**
        return webClient.post()
                .uri("/auth/validate")  // 远程调用 `comment-service` 校验 token
                .header("Authorization", "Bearer " + token)
                .retrieve()
                .bodyToMono(Boolean.class)
                .flatMap(isValid -> {
                    if (Boolean.TRUE.equals(isValid)) {
                        return chain.filter(exchange);
                    } else {
                        return unauthorizedResponse(exchange);
                    }
                })
                .onErrorResume(e -> unauthorizedResponse(exchange)); // 处理远程服务异常

    }

    private boolean skipAuth(String path) {
        return path.startsWith("/apis/admin/auth/login") ||
                path.startsWith("/apis/admin/auth/register") || path.startsWith("/apis/video/callback/video");
    }

    private boolean isInternalCall(ServerHttpRequest request) {
        return "true".equals(request.getHeaders().getFirst("Internal-Call"));
    }

    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst("Authorization");
        if (StringUtils.hasText(token) && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return null;
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("message", "未授权访问111");

        try {
            return response.writeWith(Mono.just(response.bufferFactory()
                    .wrap(new ObjectMapper().writeValueAsBytes(result))));
        } catch (JsonProcessingException e) {
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return -100;
    }
}